<template>
  <!-- 正常维护，计划检修，试验工单 -->
  <div class="workList">
    <div class="tableConten">
      <div class="tebleDiv">
        <span class="instructions">作业表单数据将会自动保存</span>
      </div>
    </div>
    <workInstruction
      ref="instruction"
      :disabled="editInstruction"
      :formData="formData"
      :workBookList="workFormData.orderInstructionBeanList"
    ></workInstruction>
    <div class="tableConten">
      <div class="itemTitle">
        <span class="redPoint">*</span>
        作业准备:
      </div>
      <div class="tebleDiv">
        <editTable
          :tableSetting="workListDetails"
          :hideBtn="hideBtn"
          ref="operationRatio"
        ></editTable>
      </div>
    </div>
    <div class="tableConten">
      <div class="itemTitle">
        <span class="redPoint">*</span>
        作业过程:
      </div>
      <div class="tebleDiv processTable" v-if="tabList.length">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <template v-for="(item, index) in tabList">
            <el-tab-pane
              :label="item.equipmentName"
              :key="'devic_' + index"
              :name="index.toString()"
            >
              <div class="parameterTable" v-if="orderType == 'experiment'">
                <div class="parameterItem">
                  <editTable
                    :tableSetting="envSetting"
                    :tableData="item.envParams"
                    :hideBtn="hideBtn"
                    ref="envTable"
                  ></editTable>
                </div>
                <div class="parameterItem">
                  <editTable
                    :tableSetting="deviceSetting"
                    :tableData="item.deviceParams"
                    :hideBtn="hideBtn"
                    ref="deviceTable"
                  ></editTable>
                </div>
              </div>
              <editTableExpand
                :tableSetting="workProcessDetails"
                :tableData="item.itemVos"
                :stepLevel="item.stepLevel"
                :hideBtn="hideBtn"
                :ref="'devic_' + index"
                rowKey="id"
              >
                <template #itemParamsBeanList="{ editFormInfo }">
                  <el-form
                    :model="itemParamsBeanList"
                    ref="ruleForm"
                    label-width="120px"
                    class="demo-ruleForm"
                  >
                    <template
                      v-for="(item, index) in editFormInfo.itemParamsBeanList"
                    >
                      <el-form-item
                        :label="item.name + '(' + item.unit + '):'"
                        prop="name"
                        :key="index"
                      >
                        <el-input
                          v-model="item.value"
                          @change="(val) => inputChange(val, item)"
                          :disabled="item.disabled"
                        ></el-input>
                      </el-form-item>
                    </template>
                  </el-form>
                </template>
              </editTableExpand>
              <div class="workForm" v-if="orderType == 'experiment'">
                <editForm
                  :formConfig="processConfig"
                  :ref="'processForm_' + index"
                  :formData="item"
                ></editForm>
                <div class="reportDiv">
                  <div class="tableConten">
                    <div class="itemTitle">
                      <span class="redPoint">*</span>
                      试验报告:
                    </div>
                    <div class="reportBtnDiv btnItem">
                      <el-button
                        class="el-button el-button--primary el-button--mini"
                        size="mini"
                        v-if="!showBtn"
                        @click="generateReport(item)"
                        >生成</el-button
                      >
                      <el-button
                        class="el-button el-button--primary el-button--mini"
                        size="mini"
                        v-if="!showBtn && haveElectronicSign"
                        @click="toSentSign(item, index)"
                        >签名</el-button
                      >
                    </div>
                    <div class="fileDiv btnItem">
                      <attachFormNew
                        :disabled="showBtn"
                        isDelete
                        coverFile
                        isInstantUpload
                        :attachSetting="reportSetting"
                        :ref="'reportForm_' + index"
                      ></attachFormNew>
                    </div>
                  </div>
                </div>
              </div>
              <div class="workForm" v-if="orderType == 'maintain'">
                <div class="lineContent">
                  <span class="lable">过程验收人：</span>
                  <span class="signatureList">
                    <template
                      v-for="(signItem, signIndex) in item.orderSignBeanList"
                    >
                      <span class="signName" :key="signIndex">{{
                        signItem.signerName
                      }}</span>
                    </template>
                  </span>
                  <span class="signatureBtn" v-if="!showBtn">
                    <el-button
                      class="el-button--plain signBtn"
                      size="mini"
                      @click="checkMaintain(item)"
                      >签名</el-button
                    >
                  </span>
                </div>
                <div class="lineContent">
                  <span class="lable">备注：</span>
                  <span class="inputContent">
                    <el-input
                      type="textarea"
                      :rows="3"
                      placeholder="请输入备注信息"
                      v-model="item.desc"
                      :disabled="showBtn"
                      @change="(val) => changeRemark(val, item)"
                    ></el-input>
                  </span>
                </div>
              </div>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
    </div>
    <div class="tableConten" v-if="orderType == 'maintain'">
      <div class="workForm">
        <editForm
          :formConfig="workConfig"
          ref="workForm"
          :formData="workFormData"
        ></editForm>
      </div>
    </div>

    <div class="tableConten">
      <div class="itemTitle">附件:</div>
      <div class="tebleDiv">
        <attachFormNew
          style="width: 60%"
          :disabled="showBtn"
          :attachSetting="attachSetting"
          isDelete
          multiple
          isInstantUpload
          ref="workFile"
        ></attachFormNew>
      </div>
    </div>

    <electronicSign
      v-if="showElectronicSign"
      :electronicData="formData"
      :electronicForm="electronicForm"
      :reportSetting="reportSetting"
      @doElectronicSign="doElectronicSign"
      :showElectronicSign.sync="showElectronicSign"
      ref="electronicSign"
    ></electronicSign>

    <signature
      v-if="showSignature"
      :signList="signList"
      @doSign="verResults"
      :showSignature.sync="showSignature"
    ></signature>
  </div>
</template>
<script>
/* 正常维护 */
import {
  getWorkListApi, //获取作业表单信息
  getWorkDeviceListApi, //根据工单Id查询作业表单-设备信息列表信息
  getDeviceListApi, //根据工单Id查询作业表单-设备以及下属项目列表信息
  getinstructionApi, //根据工单Id查询作业表单-作业指导书信息
  getDeviceTableApi, //根据工单Id,设备id查询作业表单-设备下项目信息列表信息
  getWorkReadyApi, //根据工单Id查询作业表单-作业准备信息
  saveItemParamsApi, //更新作业表单-作业过程-参数项值信息
  saveReadyApi, //更新作业表单-作业准备信息
  saveItemApi, //更新作业表单-作业过程-项目信息
  saveProcessApi, //更新作业表单-作业过程信息
  saveOperateFormItemApi, //新增或更新作业表单信息
  updateSignInfo, //更新签名信息
  updateRemarkApi, //更新作业表单-作业过程-设备信息（正常维护备注信息修改）
} from "@/api/orderManagement/normalMaintenance";
/* 计划检修 */
import {
  getWorkListApi as getRepairWorkListApi, //获取作业表单信息
  getWorkDeviceListApi as getRepairWorkDeviceListApi, //根据工单Id查询作业表单-设备信息列表信息
  getDeviceListApi as getRepairDeviceListApi, //根据工单Id查询作业表单-设备以及下属项目列表信息
  getInstructionApi as getRepairInstructionApi, //根据工单Id查询作业表单-作业指导书信息
  getDeviceTableApi as getRepairDeviceTableApi, //根据工单Id,设备id查询作业表单-设备下项目信息列表信息
  getWorkReadyApi as getRepairWorkReadyApi, //根据工单Id查询作业表单-作业准备信息
  saveItemParamsApi as saveRepairItemParamsApi, //更新作业表单-作业过程-参数项值信息
  saveReadyApi as saveRepairReadyApi, //更新作业表单-作业准备信息
  saveItemApi as saveRepairItemApi, //更新作业表单-作业过程-项目信息
  saveProcessApi as saveRepairProcessApi, //更新作业表单-作业过程信息
  saveOperateFormItemApi as saveRepairOperateFormItemApi, //新增或更新作业表单信息
  updateSignInfo as updateRepairSignInfo, //更新签名信息
} from "@/api/orderManagement/planRepair";
/* 试验工单 */
import {
  getWorkListApi as getExperimentWorkListApi, //获取作业表单信息
  updateSignInfo as updateExperimentSignInfo, //更新签名
  saveReadyApi as saveExperimentReadyApi, //更新作业表单-作业准备信息
  saveItemParamsApi as saveExperimentItemParamsApi, //更新作业表单-作业过程-参数项值信息
  saveItemApi as saveExperimentItemApi, //更新作业表单-作业过程-项目信息
  saveExperimentParamsApi, //更新作业表单-作业过程-环境,设备参数信息
  getReportApi, //查询设备,实验报告中数据
  saveOperateFormItemApi as saveExperimentFormItemApi, //新增或更新作业表单信息
  updateBatchApi, // 更新试验员（批量）
  getDeviceTableApi as getExperimentDeviceTableApi, //根据工单Id,设备id查询作业表单-设备下项目信息列表信息
  printExperimentApi,
} from "@/api/orderManagement/experimentOrder";
import { getAttachList } from "@/api/common";
import attachFormNew from "@/components/attach/attachFormNew";
import editTableExpand from "../editTableExpand";
import signature from "@/components/signature";
import electronicSign from "../electronicSign";
import workInstruction from "../publicModule/workInstruction"; /* 作业指导书 */
export default {
  props: {
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //是否可编辑
    isEdit: {
      type: Boolean,
      default: false,
    },
    //工单类型
    orderType: {
      type: String,
      default: null,
    },
    pageType: {
      type: String,
      default: "",
    },
  },
  components: {
    attachFormNew,
    signature,
    electronicSign,
    editTableExpand,
    workInstruction,
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      activeName: "0",
      showSignature: false,
      editInstruction: true,
      showElectronicSign: false,
      saveTime: "",
      operatorList: [],
      signList: [],
      tabList: [],
      workFormData: {},
      electronicForm: [], // 电子签表格数据 姓名 手机号
      electronicData: {}, // 电子签其他数据
      workConfig: {
        itemArr: [
          {
            label: "存在问题:",
            prop: "problem",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            methods: (val, obj) => {
              this.saveOperateForm(obj);
            },
          },
          {
            label: "改进建议:",
            prop: "opinion",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            methods: (val, obj) => {
              this.saveOperateForm(obj);
            },
          },
        ],
      },
      processConfig: {
        itemArr: [
          {
            label: "备注及结论:",
            prop: "conclusion",
            type: "textarea",
            maxlength: "500",
            span: 24,
            rows: 4,
            methods: (val, obj) => {
              this.saveExperimentForm(obj);
            },
          },
          {
            type: "select",
            label: "是否合格",
            prop: "passStatus",
            required: true,
            selectOption: [
              {
                name: "合格",
                label: "合格",
                value: "1",
              },
              {
                name: "不合格",
                label: "不合格",
                value: "0",
              },
            ],
            methods: (obj) => {
              this.saveExperimentForm(obj);
            },
            span: 8,
          },
          {
            label: "试验员",
            prop: "experimenterName", //多选时，字段要为数组类型
            propArr: "experimenterArr",
            idsStr: "experimenter",
            multiple: true, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {
              let equipmentData = this.tabList[this.activeName];
              let { id: experimentEquipmentId } = equipmentData;
              let operatorList = [];
              obj.map((i) => {
                let { name, id, isOutOrg, phone } = i;
                var isPhone = /^((\+?86)|(\(\+86\)))?(13[012356789][0-9]{8}|15[012356789][0-9]{8}|18[02356789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
                phone = isPhone.test(phone) ? phone : "";
                let type = "";
                switch (isOutOrg) {
                  case "0":
                    type = "employee";
                    break; //本单位
                  case "1":
                    type = "outsource";
                    break; //外单位
                  case "-1":
                    type = "temp";
                    break; //外单位
                }
                let item = {
                  account: id,
                  name,
                  type,
                  phone,
                  experimentId: this.formData.id,
                  experimentEquipmentId,
                };
                operatorList.push(item);
              });
              this.operatorList = operatorList;
              this.updateOperator(operatorList);
            },
            required: true,
            span: 8,
            rows: 2,
          },
        ],
      },
      currentLineDevice: {}, //当前设备
      currentRow: null, //当前行
      typeId: null,

      hideBtn: false,
      workListData: [],
      itemParamsBeanList: {},
      rules: [],
      workProcessData: [],
      /* 作业表单-作业准备 */
      workListDetails: {
        title: "",
        select: false,
        showIndex: true,
        addMethons: false,
        showCheckbox: false,
        maxHeight: 400,
        btnArr: [], //"edit",
        data: [],
        column: [
          {
            label: "类别",
            prop: "type",
            type: "disableText",
          },
          {
            label: "名称",
            prop: "tools",
            type: "disableText",
          },
          {
            label: "确认状态",
            prop: "result",
            type: "checkbox",
            width: 180,
            method: (obj, item) => {
              this.confirmStatus(obj, item);
            },
          },
        ],
      },
      /* 作业表单-作业过程下设备参数列表 */
      deviceSetting: {
        title: "",
        select: false,
        addMethons: false,
        showCheckbox: false,
        showIndex: true,
        maxHeight: 400,
        btnArr: [], //"edit",
        data: [],
        column: [
          {
            label: "设备参数",
            prop: "name",
            type: "disableText",
            width: 180,
          },
          {
            label: "参数值",
            prop: "value",
            type: "text",
            method: (obj, item) => {
              this.updateParams(obj, item);
            },
          },
        ],
      },
      /* 作业表单-作业过程下环境参数列表 */
      envSetting: {
        title: "",
        select: false,
        addMethons: false,
        showCheckbox: false,
        showIndex: true,
        maxHeight: 400,
        btnArr: [], //"edit",
        data: [],
        column: [
          {
            label: "环境参数",
            prop: "name",
            type: "disableText",
            width: 180,
          },
          {
            label: "参数值",
            prop: "value",
            type: "text",
            method: (obj, item) => {
              this.updateParams(obj, item);
            },
          },
        ],
      },
      /* 作业表单-作业过程 */
      workProcessDetails: {
        title: "",
        select: false,
        addMethons: false,
        showOrder: false,
        showCheckbox: false,
        maxHeight: 800,
        btnArr: [],
        column: [
          {
            label: "序号",
            prop: "serialNum",
            width: "60px",
            type: "disableText",
          },
          {
            label: "作业内容",
            prop: "context",
            width: "200px",
            type: "disableText",
          },
          {
            label: "作业标准",
            prop: "contextStandard",
            //width: "280px",
            type: "disableText",
          },
          {
            label: "作业风险&控制措施",
            prop: "risk",
            //width: "260px",
            type: "disableText",
          },
          {
            label: "数据记录项",
            prop: "itemParamsBeanList",
            width: "250px",
          },
          {
            label: "验收级别",
            prop: "level",
            width: "150px",
            type: "disableText",
            formatter: (val, row) => {
              let level = val || 0;
              return this.option[level] || " ";
            },
          },
          {
            label: "确认状态",
            prop: "result",
            width: "180px",
            type: "checkbox",
            methods: (obj, item) => {
              this.confirmProcessStatus(obj, item, "result");
            },
          },
          {
            label: "备注",
            prop: "desc",
            type: "textarea",
            width: "220px",
            methods: (obj, item) => {
              this.confirmProcessStatus(obj, item, "desc");
            },
          },
          {
            label: "已签名人",
            prop: "signerName",
            type: "disableText",
          },
        ],
        buttonArr: [
          {
            name: "验收签名",
            isShow: (row) => {
              return true;
            },
            methods: (row, index) => {
              //判断内容是否填写完整
              let canSign = true;
              let mes = "";
              let { itemParamsBeanList, result } = row;
              if (result != true) {
                mes = "状态未确认!";
                canSign = false;
              } else {
                for (let i = 0; i < itemParamsBeanList.length; i++) {
                  if (itemParamsBeanList[0].value == null) {
                    mes = "数据记录项未填写完整！";
                    canSign = false;
                    break;
                  }
                }
              }
              if (canSign) {
                this.currentRow = row;
                let signList = row.orderSignBeanList || [];
                this.signList = [];
                signList.map((i) => {
                  this.signList.push(i.signer);
                });
                this.showSignature = true;
              } else {
                this.$message.warning(mes);
              }
            },
          },
        ],
      },

      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "workList",
      },
      //报告设置
      reportSetting: {
        businessId: "", //单据的ID
        subBusinessId: "", //设备ID
        businessType: "report",
        btnName: "上传试验报告",
      },
      isComplete: true,
      locationInfo: null,
      option: {
        1: "Ⅰ",
        2: "Ⅱ",
        3: "Ⅲ",
      },
    };
  },
  computed: {
    showBtn() {
      return !(this.formData.status == "IN_EXECUTE" && this.pageType == "edit");
    },
    showBookList() {
      let bookLength = this.workFormData.orderInstructionBeanList || [];
      return bookLength != 0;
    },
    haveElectronicSign() {
      let userSignType = this.$store.getters.userSignType;
      return userSignType == "electronic";
    },
  },
  watch: {
    formData: {
      handler(val) {
        this.attachSetting.businessId = val.id; //作业表单附件
      },
      deep: true,
    },
    "formData.status": {
      handler(val) {
        //更新数据
        this.init();
      },
      deep: true,
    },
    activeName: {
      handler(val) {
        if (this.orderType == "experiment") {
          this.reportSetting.subBusinessId = this.tabList[this.activeName].id;
        }
      },
    },
    isEdit: {
      handler(val) {
        if (val) {
          this.hideBtn = false;
        } else {
          this.hideBtn = true;
        }
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {
    this.init(); //调试用
  },
  methods: {
    init() {
      let status = this.formData.status;
      this.attachSetting.businessId = this.formData.id; //作业表单附件
      this.reportSetting.businessId = this.formData.id; //试验报告
      if (status != "IN_EXECUTE") {
        this.hideBtn = true;
      } else {
        this.hideBtn = false;
      }
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        //作业过程的表格不做签名操作
        let arr = [];
        this.workProcessDetails.column.map((i) => {
          if (!["desc", "signerName"].includes(i.prop)) {
            arr.push(i);
          }
        });
        this.workProcessDetails.column = arr;
        this.workProcessDetails.buttonArr = [];
      }
      if (this.formData.id) {
        this.getWorkList();
      }
    },
    //判断是否填写完整
    async judgeComplete() {
      await this.getWorkList("judgeComplete");
      let result = {
        isComplete: this.isComplete,
        message: this.locationInfo,
      };
      return result;
    },
    //获取作业表单信息
    async getWorkList(type) {
      this.isComplete = true;
      //this.tabList = [];
      this.locationInfo = null;
      var actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        actionApi = getWorkListApi;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        actionApi = getExperimentWorkListApi;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        actionApi = getRepairWorkListApi;
      }
      let res = await actionApi(this.formData.id);
      let data = res.data;
      this.workFormData = Object.assign({}, data);
      let readyPoList = [];
      let equipmentVoList = [];
      let readyPoListComplete = true;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        readyPoList = data.maintainReadyPoList || [];
        equipmentVoList = data.maintainEquipmentVoList || [];
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        readyPoList = data.experimentReadyPoList || [];
        equipmentVoList = data.experimentEquipmentVoList || [];
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        readyPoList = data.repairReadyPoList || [];
        equipmentVoList = data.repairEquipmentVoList || [];
      }
      this.tabList = equipmentVoList;
      /* 作业准备表格数据 - 可编辑*/
      readyPoList.map((i) => {
        if (this.formData.status == "IN_EXECUTE" && this.pageType == "edit") {
          i.editable = true;
        }
        /* 判断是否填写完整 */
        if (i.result == 0) {
          this.isComplete = false;
          this.locationInfo = "作业准备未确认完！";
        }
      });
      if (this.$refs.operationRatio) {
        this.$refs.operationRatio.setTableData(readyPoList);
      }

      /* 作业过程数据 */
      let option = [];
      if (this.orderType == "experiment") {
        this.reportSetting.subBusinessId = equipmentVoList[this.activeName].id;
      }
      equipmentVoList.map((i, index) => {
        let equipmentName = i.equipmentName || "";
        if (equipmentName) {
          equipmentName = equipmentName + "：";
        }
        let itemList = [];
        if (this.orderType == "experiment") {
          if (i.itemVos.length > 0) {
            itemList = i.itemVos[0].experimentItemVoList || [];
          }
          //试验工单
          let deviceParams = i.deviceParams || []; //作业过程下设备参数列表
          let envParams = i.envParams || []; //作业过程下环境参数列表

          //试验员列表
          let nameArr = [];
          let idsArr = [];
          let typeArr = [];
          if (i.equipmentSignPos.length > 0) {
            i.equipmentSignPos.map((j) => {
              nameArr.push(j.name);
              idsArr.push(j.account);
              typeArr.push(j.type);
            });
            i.experimenterName = nameArr.toString();
            i.experimenterArr = idsArr;
            i.experimenter = idsArr.toString();
            let isOut = this.$utils.changeType(typeArr);
            option[index] = this.$utils.getOptionData(
              nameArr.toString(),
              idsArr.toString(),
              isOut.toString()
            );
          }

          /* 验证试验工单环境参数、设备参数是否填写完整 */
          envParams.map((j) => {
            if (
              this.formData.status == "IN_EXECUTE" &&
              this.pageType == "edit"
            ) {
              j.editable = true;
            } else {
              j.editable = false;
            }
            if ([null, ""].includes(j.value) && this.locationInfo == null) {
              this.isComplete = false;
              this.locationInfo = i.equipmentName + "：环境参数未填写完整！";
            }
          });
          deviceParams.map((j) => {
            if (
              this.formData.status == "IN_EXECUTE" &&
              this.pageType == "edit"
            ) {
              j.editable = true;
            } else {
              j.editable = false;
            }
            if ([null, ""].includes(j.value) && this.locationInfo == null) {
              this.isComplete = false;
              this.locationInfo = i.equipmentName + "：设备参数未填写完整！";
            }
          });
          this.$nextTick(() => {
            this.$refs[`processForm_${index}`][0]
              .getFormData()
              .then((res) => {
                this.isComplete = true;
              })
              .catch((error) => {
                this.isComplete = false;
                this.locationInfo =
                  i.equipmentName + "作业过程表单未填写完整！";
              });
            let fileData =
              this.$refs[`reportForm_${index}`][0].getFileListData() || [];
            if (fileData.length > 0) {
              this.isComplete = true;
            } else {
              this.isComplete = false;
              this.locationInfo = i.equipmentName + "试验报告未上传！";
            }
          });
        } else if (this.orderType == "maintain") {
          if (i.itemVos.length > 0) {
            itemList = i.itemVos[0].maintainItemVoList || [];
          }
        } else if (this.orderType == "repair") {
          if (i.itemVos.length > 0) {
            itemList = i.itemVos[0].repairItemVoList || [];
          }
        }
        if (itemList.length > 0) {
          i.stepLevel = 2;
        } else {
          i.stepLevel = 1;
        }
        i.itemVos.map((j, index) => {
          j.children = [];
          j.serialNum = index + 1;
          //数据记录项信息
          if (this.orderType == "experiment") {
            //试验工单
            j.children = j.experimentItemVoList || [];
          } else if (this.orderType == "maintain") {
            j.children = j.maintainItemVoList || [];
          } else if (this.orderType == "repair") {
            j.children = j.repairItemVoList || [];
          }
          //下一层级
          j.children.map((item, childIndex) => {
            let num = childIndex + 1;
            let name = [];
            if (this.orderType != "maintain") {
              item.orderSignBeanList.map((k) => {
                name.push(k.signerName);
              });
              item.signerName = name.toString();
            }

            item.serialNum = j.serialNum + "." + num;
            if (
              this.formData.status == "IN_EXECUTE" &&
              this.pageType == "edit"
            ) {
              item.editable = true;
            }
            if (this.formData.status == "IN_EXECUTE") {
              //作业过程确认、签名验证
              if (i.stepLevel == 2 && this.isComplete) {
                if (item.result == 0 && this.locationInfo == null) {
                  this.isComplete = false;
                  this.locationInfo =
                    equipmentName +
                    item.serialNum +
                    item.context +
                    "：作业过程未确认完！";
                }
                if (this.orderType != "maintain") {
                  if (
                    item.orderSignBeanList.length == 0 &&
                    this.locationInfo == null
                  ) {
                    this.isComplete = false;
                    this.locationInfo =
                      equipmentName +
                      item.serialNum +
                      item.context +
                      "：未做验收签名！";
                  }
                }
              }
              item.itemParamsBeanList.map((k) => {
                if (this.pageType == "edit") {
                  k.disabled = false;
                } else {
                  k.disabled = true;
                }
                /* 判断是否填写完整 */
                if (this.isComplete && i.stepLevel == 2) {
                  if (
                    [null, undefined].includes(k.value) &&
                    this.locationInfo == null
                  ) {
                    this.isComplete = false;
                    this.locationInfo =
                      equipmentName + "：数据记录项未填写完！";
                  }
                }
              });
            } else {
              item.itemParamsBeanList.map((k) => {
                k.disabled = true;
              });
            }
          });
          if (this.formData.status == "IN_EXECUTE" && this.pageType == "edit") {
            j.editable = true;
          }
          let name = [];
          /* 判断是否填写完整 */
          if (this.isComplete && i.stepLevel == 1) {
            if (j.result == 0 && this.locationInfo == null) {
              this.isComplete = false;
              this.locationInfo =
                equipmentName +
                j.serialNum +
                j.context +
                "：作业过程未确认完！";
            }
            if (this.orderType != "maintain") {
              if (
                j.orderSignBeanList.length == 0 &&
                this.locationInfo == null
              ) {
                this.isComplete = false;
                this.locationInfo =
                  equipmentName + j.serialNum + j.context + "：未做验收签名！";
              }
            }
          }
          if (this.orderType != "maintain") {
            j.orderSignBeanList.map((k) => {
              name.push(k.signerName);
            });
          }
          j.signerName = name.toString();
          if (this.formData.status == "IN_EXECUTE") {
            j.itemParamsBeanList.map((k) => {
              /* 判断是否填写完整 */
              if (this.isComplete) {
                if (
                  [null, undefined].includes(k.value) &&
                  this.locationInfo == null
                ) {
                  this.isComplete = false;
                  this.locationInfo = equipmentName + "：数据记录项未填写完！";
                }
              }
              if (this.pageType == "edit") {
                k.disabled = false;
              } else {
                k.disabled = true;
              }
            });
          } else {
            j.itemParamsBeanList.map((k) => {
              k.disabled = true;
            });
          }
        });
      });

      //设置试验员的选项值
      this.$nextTick(() => {
        option.map((i, index) => {
          this.$refs["processForm_" + index][0].setItemOption(
            "experimenterName",
            i
          );
        });
      });
      if (this.formData.status == "IN_EXECUTE" && this.pageType == "edit") {
        //可编辑
        this.workProcessDetails.column.map((i) => {
          i.disabled = false;
          if (i.prop == "action") {
            i.isHide = false;
          }
        });
        this.workListDetails.column.map((i) => {
          i.disabled = false;
        });
        this.workConfig.itemArr.map((i) => {
          i.disabled = false;
        });
        this.processConfig.itemArr.map((i) => {
          i.disabled = false;
        });
      } else {
        //不可编辑
        this.workProcessDetails.column.map((i) => {
          i.disabled = true;
          if (i.prop == "action") {
            i.isHide = true;
          }
        });
        this.workListDetails.column.map((i) => {
          i.disabled = true;
        });
        this.workConfig.itemArr.map((i) => {
          i.disabled = true;
        });
        this.processConfig.itemArr.map((i) => {
          i.disabled = true;
        });
        // }
      }
    },
    // 转换作业过程数据
    changeItemVos(itemVos) {
      itemVos.map((j, index) => {
        j.children = [];
        j.serialNum = index + 1;
        //数据记录项信息
        if (this.orderType == "experiment") {
          //试验工单
          j.children = j.experimentItemVoList || [];
        } else if (this.orderType == "maintain") {
          j.children = j.maintainItemVoList || [];
        } else if (this.orderType == "repair") {
          j.children = j.repairItemVoList || [];
        }
        //下一层级
        j.children.map((item, childIndex) => {
          item.editable = true;
          let num = childIndex + 1;
          let name = [];
          item.orderSignBeanList.map((k) => {
            name.push(k.signerName);
          });
          item.signerName = name.toString();
          item.serialNum = j.serialNum + "." + num;
        });
        if (j.children.length == 0) {
          j.editable = true;
        }
        let name = [];
        j.orderSignBeanList.map((k) => {
          name.push(k.signerName);
        });
        j.signerName = name.toString();
      });
      this.$refs["devic_" + this.activeName][0].setTableData(itemVos);
    },
    changeTableData(data) {
      data.map((i) => {
        i.editable = true;
      });
    },
    //新增作业表单
    addWorkList(data, hadData) {
      let rowIndex = this.workListData.rowIndex;
      data.rowIndex = hadData.length + 1;
      // data.partSource = "spare_part";
      data.action = "删除";
      hadData.push(data);
      this.$refs.workListTable.setTableData(hadData);
    },
    handleClick(tab, event) {},
    handleDelete() {},

    async getWorkListData() {
      let workListData = await this.$refs.workListTable.getTableData();
      workListData.map((i, index) => {
        delete i.action;
        i.sort = index;
      });
      return workListData;
    },
    async getworkProcessData() {
      let workProcessData = await this.$refs.workProcessTable.getTableData();
      workProcessData.map((i, index) => {
        delete i.isChange;
        delete i.type;
        i.sort = index;
      });
      return workProcessData;
    },
    //确认作业状态
    confirmStatus(obj, item) {
      let { id, result } = obj;
      let form = {
        id,
        result,
      };
      var actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        actionApi = saveReadyApi;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        actionApi = saveExperimentReadyApi;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        actionApi = saveRepairReadyApi;
      }
      actionApi(form).then((res) => {
        this.updataTime();
      });
    },
    //更新作业表单-作业过程-环境,设备参数信息
    updateParams(obj, item) {
      // let { id, name, value } = obj;
      saveExperimentParamsApi(obj).then((res) => {
        this.updataTime();
      });
    },
    /* 数据记录项修改 */
    inputChange(val, item) {
      let { id, value } = item;
      let form = {
        id,
        value,
      };
      var actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        actionApi = saveItemParamsApi;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        actionApi = saveExperimentItemParamsApi;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        actionApi = saveRepairItemParamsApi;
      }
      actionApi(form).then((res) => {
        this.updataTime();
      });
    },
    //确认过程状态
    confirmProcessStatus(obj, item, type) {
      let form = { id: obj.id };
      form[type] = obj[type];
      if (type == "result") {
        form.desc = obj.desc;
      } else if (type == "desc") {
        form.result = obj.result;
      }
      var actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        actionApi = saveItemApi;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        actionApi = saveExperimentItemApi;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        actionApi = saveRepairItemApi;
      }
      actionApi(form).then((res) => {
        this.updataTime();
      });
    },
    //正常维护修改作业表单FORM
    async saveOperateForm(obj) {
      let data = await this.$refs.workForm.getFormData();
      let { problem, opinion } = data;
      let form = {
        id: this.formData.id,
        opinion,
        problem,
      };
      saveOperateFormItemApi(form).then((res) => {
        this.updataTime();
      });
    },
    //试验工单修改作业表单FORM
    async saveExperimentForm() {
      let data = await this.$refs[
        "processForm_" + this.activeName
      ][0].getFormData(false);
      let { equipmentId, id } = this.tabList[this.activeName];
      let { conclusion, passStatus } = data;
      let form = {
        experimentId: this.formData.id,
        id,
        equipmentId,
        conclusion,
        passStatus,
      };
      saveExperimentFormItemApi(form).then((res) => {
        this.updataTime();
      });
    },
    //试验工单更新试验员信息
    updateOperator(obj) {
      updateBatchApi(obj).then((res) => {
        this.updataTime();
      });
    },
    //试验报告-生成报告
    generateReport(item) {
      let form = {
        experimentEquipmentId: item.id,
        standardId: item.standardId, //打印模板ID
      };
      printExperimentApi(form).then((res) => {
        if (res.data) {
          window.open(res.data);
        }
      });
    },

    //正常维护签名
    checkMaintain(data) {
      this.currentRow = data;
      let form = {
        orderId: this.formData.id,
        maintainEquipmentId: data.id,
      };
      let canSign = true;
      let locationInfo = null; // getDeviceTableApi
      getDeviceListApi(form).then((res) => {
        let data = res.data || [];
        /* 作业过程表格数据 */
        let tableData = data[0].itemVos || [];
        //获取已签名人
        this.signList = [];
        data[0].orderSignBeanList.map((i) => {
          this.signList.push(i.signer);
        });
        tableData.map((i) => {
          /* 只有一层 */
          if (i.level == 1) {
            /* 数据记录项 */
            i.itemParamsBeanList.map((k) => {
              if ([null, undefined].includes(k.value) && canSign) {
                canSign = false;
                locationInfo = i.equipmentName;
                i.serialNum + i.context + "数据记录变量未填写完！";
              }
            });
            /* 作业过程确认 */
            if (i.result == 0 && canSign) {
              canSign = false;
              locationInfo =
                i.equipmentName +
                i.serialNum +
                i.context +
                "作业过程未确认完！";
            }
          } else if (i.level == 2) {
            /* 有两层 */
            i.maintainItemVoList.map((j) => {
              /* 数据记录项 */
              j.itemParamsBeanList.map((k) => {
                if ([null, undefined].includes(k.value) && canSign) {
                  canSign = false;
                  locationInfo =
                    i.equipmentName +
                    j.serialNum +
                    j.context +
                    "数据记录变量未填写完！";
                }
              });
              /* 作业过程确认 */
              if (j.result == 0 && canSign) {
                canSign = false;
                locationInfo =
                  i.equipmentName +
                  j.serialNum +
                  j.context +
                  "作业过程未确认完！";
              }
            });
          }
        });
        if (canSign) {
          this.showSignature = true;
        } else {
          this.$message.warning(locationInfo);
        }
      });
    },
    //签名（电子）
    toSentSign(item, index) {
      let fileData = this.$refs[`reportForm_${index}`].getFileListData() || [];
      if (fileData.length > 0) {
        this.electronicForm = this.tabList[this.activeName].equipmentSignPos;
        this.showElectronicSign = true;
      } else {
        this.$message.warning("请先上传试验报告！");
      }
    },
    // 电子签名
    async doElectronicSign(data) {
      // console.log(data);
    },

    updataTime() {
      this.saveTime = this.$utils.getCurrentDate();
    },
    //选择设备
    selectWorkStandard() {},

    //保存附件
    saveAttachFile() {
      this.$refs.workFile.save();
    },
    //签名
    verResults(obj) {
      let { account, name } = obj;
      //判断是否重复签名
      let form = {
        orderType: this.orderType,
        signer: account,
        signerName: name,
        orderId: this.formData.id,
        itemId: this.currentRow.id,
      };
      let actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        actionApi = updateSignInfo;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        actionApi = updateExperimentSignInfo;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        actionApi = updateRepairSignInfo;
      }
      actionApi(form).then((res) => {
        //重新获取当前设备的数据
        this.getDevicedata();
      });
    },
    //更新当前设备的作业过程数据
    getDevicedata() {
      let form = {
        orderId: this.formData.id,
      };
      let actionApi = null;
      if (this.orderType == "maintain") {
        /* 正常维护单 */
        form.maintainEquipmentId = this.currentRow.id;
        actionApi = getDeviceListApi;
      } else if (this.orderType == "experiment") {
        /* 试验工单 */
        form.experimentEquipId = this.currentRow.experimentEquipId;
        actionApi = getExperimentDeviceTableApi;
      } else if (this.orderType == "repair") {
        /* 计划检修 */
        form.repairEquipmentId = this.currentRow.repairEquipId;
        actionApi = getRepairDeviceTableApi;
      }
      actionApi(form).then((res) => {
        let data = res.data;
        if (this.orderType == "maintain") {
          let orderSignBeanList = data[0].orderSignBeanList || [];
          this.tabList[this.activeName].orderSignBeanList = orderSignBeanList;
        } else {
          this.changeItemVos(data); //数据转换
        }
      });
    },
    //正常维护备注信息修改
    changeRemark(val, data) {
      let form = {
        id: data.id,
        maintainId: data.maintainId,
        equipmentId: data.equipmentId,
        equipmentName: data.equipmentName,
        desc: val,
      };
      updateRemarkApi(form).then((res) => {
        this.updataTime();
      });
    },
  },
};
</script>
<style lang="less">
.workList {
  .tableConten {
    display: flex;
    flex-flow: wrap nowrap;
    margin-top: 15px;
    .redPoint {
      color: red;
    }
    .itemTitle {
      width: 95px;
      text-align: justify;
      text-align-last: justify;
      padding-right: 10px;
    }
    .tebleDiv {
      width: calc(100% - 87px);
      text-align: left;
    }
    .el-tabs__item {
      height: 30px;
      line-height: 30px;
    }
    .btnItem + .btnItem {
      margin-right: 15px;
    }
    .signatureBtn {
      margin-left: 20px;
    }
    .signName + .signName {
      margin-left: 20px;
    }
    .lineContent {
      display: flex;
      flex-flow: wrap nowrap;

      .lable {
        width: 80px;
        height: 40px;
        line-height: 40px;
        text-align: right;
        margin-right: 15px;
      }
      .signatureList {
        height: 40px;
        line-height: 40px;
      }
      .signatureBtn {
        height: 40px;
        line-height: 40px;
      }
      .signBtn {
      }
      .inputContent {
        width: calc(100% - 80px);
      }
    }
    .lineContent + .lineContent {
      margin-top: 15px;
    }
  }
  .saveTime {
    color: #bebebe;
    font-size: 12px;
  }
  .instructions {
    width: 200px;
    height: 25px;
    line-height: 25px;
    margin-bottom: 10px;
  }
  .processTable {
    .el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
  .bookContent {
    width: 400px;
    border: 1px solid #ebebeb;
    border-radius: 4px;
    padding: 10px;
  }
  .line {
    height: 30px;
    width: 100%;
    border: 1px dashed #ebebeb;
    padding: 0px 10px;
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
  }
  .line + .line {
    margin-top: 10px;
  }
  .workForm {
    width: 100%;
    .el-form-item__label {
      width: 87px !important;
      // text-align: left;
    }
    .el-form-item__content {
      margin-left: 87px !important;
    }
  }
  .el-checkbox__inner::after {
    height: 10px;
    left: 7px;
    width: 4px;
  }
  .parameterTable {
    width: 100%;
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
    .parameterItem {
      width: 49%;
    }
  }
  .reportDiv {
    margin-left: 15px;
  }
  .fileDiv {
    margin-left: 15px;
    width: 500px;
    .el-upload-list {
      margin-left: -140px;
    }
  }
}
</style>
